import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export interface VideoHistory {
  url: string
  title: string
  thumbnail?: string
  duration?: number
  lastPlayed: Date
  progress: number
}

export interface VideoFilter {
  brightness: number
  contrast: number
  saturation: number
  hue: number
  blur: number
  grayscale: number
  sepia: number
  invert: number
}

export interface AudioEffect {
  name: string
  type: string
  enabled: boolean
  settings: Record<string, any>
}

export const usePlayerStore = defineStore('player', () => {
  // 播放器状态
  const currentUrl = ref('')
  const currentTitle = ref('')
  const isPlaying = ref(false)
  const currentTime = ref(0)
  const duration = ref(0)
  const volume = ref(1)
  const playbackRate = ref(1)
  const isFullscreen = ref(false)
  
  // 历史记录
  const history = ref<VideoHistory[]>([])
  
  // 批量播放
  const batchUrls = ref<string[]>([])
  const currentBatchIndex = ref(0)
  
  // 视频滤镜
  const filters = ref<VideoFilter>({
    brightness: 100,
    contrast: 100,
    saturation: 100,
    hue: 0,
    blur: 0,
    grayscale: 0,
    sepia: 0,
    invert: 0
  })
  
  // 音频效果
  const audioEffects = ref<AudioEffect[]>([
    { name: '蝰蛇音效', type: 'viper', enabled: false, settings: {} },
    { name: '3D丽音', type: '3d_audio', enabled: false, settings: {} },
    { name: '5.1全景', type: 'surround_51', enabled: false, settings: {} },
    { name: '麒麟音效', type: 'kylin', enabled: false, settings: {} },
    { name: '汽车音效', type: 'car', enabled: false, settings: {} },
    { name: 'FREEBUDS', type: 'freebuds', enabled: false, settings: {} },
    { name: 'HIFI现场', type: 'hifi_live', enabled: false, settings: {} },
    { name: '演唱会', type: 'concert', enabled: false, settings: {} }
  ])
  
  // 计算属性
  const filterStyle = computed(() => {
    const f = filters.value
    return {
      filter: `
        brightness(${f.brightness}%) 
        contrast(${f.contrast}%) 
        saturate(${f.saturation}%) 
        hue-rotate(${f.hue}deg) 
        blur(${f.blur}px) 
        grayscale(${f.grayscale}%) 
        sepia(${f.sepia}%) 
        invert(${f.invert}%)
      `.trim()
    }
  })
  
  const currentHistory = computed(() => 
    history.value.find(h => h.url === currentUrl.value)
  )
  
  // 方法
  const setCurrentUrl = (url: string) => {
    currentUrl.value = url
  }
  
  const setCurrentTitle = (title: string) => {
    currentTitle.value = title
  }
  
  const addToHistory = (url: string, title?: string) => {
    const existingIndex = history.value.findIndex(h => h.url === url)
    const historyItem: VideoHistory = {
      url,
      title: title || url,
      lastPlayed: new Date(),
      progress: 0
    }
    
    if (existingIndex >= 0) {
      history.value.splice(existingIndex, 1)
    }
    
    history.value.unshift(historyItem)
    
    // 限制历史记录数量
    if (history.value.length > 1000) {
      history.value = history.value.slice(0, 1000)
    }
    
    saveHistory()
  }
  
  const removeFromHistory = (url: string) => {
    history.value = history.value.filter(h => h.url !== url)
    saveHistory()
  }
  
  const clearHistory = () => {
    history.value = []
    saveHistory()
  }
  
  const saveHistory = () => {
    localStorage.setItem('videoHistory', JSON.stringify(history.value))
  }
  
  const loadHistory = () => {
    const saved = localStorage.getItem('videoHistory')
    if (saved) {
      history.value = JSON.parse(saved)
    }
  }
  
  const addBatchUrls = (urls: string[]) => {
    batchUrls.value.push(...urls.filter(url => !batchUrls.value.includes(url)))
  }
  
  const clearBatchUrls = () => {
    batchUrls.value = []
    currentBatchIndex.value = 0
  }
  
  const saveBatchList = () => {
    localStorage.setItem('batchUrls', JSON.stringify(batchUrls.value))
  }
  
  const loadBatchList = () => {
    const saved = localStorage.getItem('batchUrls')
    if (saved) {
      batchUrls.value = JSON.parse(saved)
    }
  }
  
  const setFilter = (filterName: keyof VideoFilter, value: number) => {
    filters.value[filterName] = value
  }
  
  const resetFilters = () => {
    filters.value = {
      brightness: 100,
      contrast: 100,
      saturation: 100,
      hue: 0,
      blur: 0,
      grayscale: 0,
      sepia: 0,
      invert: 0
    }
  }
  
  const toggleAudioEffect = (effectName: string) => {
    const effect = audioEffects.value.find(e => e.name === effectName)
    if (effect) {
      effect.enabled = !effect.enabled
    }
  }
  
  const initializePlayer = () => {
    loadHistory()
    loadBatchList()
  }
  
  // API调用
  const parseUrl = async (url: string) => {
    const response = await axios.post('/api/media/parse', { url })
    return response.data
  }
  
  const getMediaInfo = async (url: string) => {
    const response = await axios.get('/api/media/info', { params: { url } })
    return response.data
  }
  
  const getQualities = async (url: string) => {
    const response = await axios.get('/api/media/qualities', { params: { url } })
    return response.data.qualities
  }
  
  return {
    // 状态
    currentUrl,
    currentTitle,
    isPlaying,
    currentTime,
    duration,
    volume,
    playbackRate,
    isFullscreen,
    history,
    batchUrls,
    currentBatchIndex,
    filters,
    audioEffects,
    
    // 计算属性
    filterStyle,
    currentHistory,
    
    // 方法
    setCurrentUrl,
    setCurrentTitle,
    addToHistory,
    removeFromHistory,
    clearHistory,
    addBatchUrls,
    clearBatchUrls,
    saveBatchList,
    loadBatchList,
    setFilter,
    resetFilters,
    toggleAudioEffect,
    initializePlayer,
    parseUrl,
    getMediaInfo,
    getQualities
  }
})
